package cn.texous.util.commons.util;

import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * insert description here
 *
 * @author leven
 * @since 2019/5/12 19:54
 */
public class HttpUtils {

    /**
     * 根据地址获得数据的输入流
     *
     * @param strUrl 网络连接地址
     * @return url的输入流
     */
    public static InputStream getInputStreamByUrl(String strUrl) {
        try {
            URL url = new URL(strUrl);
            return url.openStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * map中的数据需要预先 url编码（如果有需要的话）
     *
     * @param url    url
     * @param params 路径参数
     * @return
     */
    public static String addUrlParams(String url, Map<String, String> params) {
        if (CollectionUtils.isEmpty(params))
            return url;

        StringBuilder stringBuilder = new StringBuilder(url);
        if (url.indexOf("?") < 0) {
            stringBuilder.append("?");
        }
        Optional.ofNullable(params)
                .map(Map::entrySet)
                .ifPresent(p ->
                        p.forEach(item ->
                                stringBuilder.append(item.getKey())
                                        .append("=")
                                        .append(item.getValue())
                                        .append("&")
                        ));
        String result = stringBuilder.substring(0, stringBuilder.length() - 1);
        return result;
    }

    /**
     * 参数替换
     *
     * @param url         路劲
     * @param params      参数
     * @param urlEncoding 编码
     * @return
     */
    public static String replaceParams(String url, Map<String, String> params, String urlEncoding) {
        Map<String, String> stringMap = params;
        if (urlEncoding != null)
            stringMap = encoderParams(stringMap, urlEncoding);
        ReplaceUtils.ReplaceParam replaceParam =
                ReplaceUtils.ReplaceParam.builder()
                        .params(stringMap)
                        .resource(url)
                        .build();
        return ReplaceUtils.replace(replaceParam);
    }

    /**
     * 参数编码
     *
     * @param params  参数
     * @param charset 编码
     * @return
     */
    public static Map<String, String> encoderParams(Map<String, String> params, String charset) {
        Map<String, String> result = new HashMap<>();
        Optional.ofNullable(params)
                .map(Map::entrySet)
                .ifPresent(p -> p.forEach(item -> {
                    if (item.getKey() != null && item.getValue() != null)
                        result.put(item.getKey(), urlEncode(item.getValue(), charset));
                }));
        return result;
    }

    /**
     * url encode
     *
     * @param value   value
     * @param charset charset
     * @return
     */
    public static String urlEncode(String value, String charset) {
        try {
            return URLEncoder.encode(value, charset);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

}
